const express = require("express");
const mongoose = require("mongoose");
const authRouter = require("./routers/auth");
const roleRouter = require("./routers/role");
const adminRouter = require("./routers/admin");
const md5 = require("md5");
const libraryRouter = require("./routers/library")

// 连接数据库
mongoose
  .connect("mongodb://127.0.0.1:27017/app")
  .then(async () => {
    console.log("数据库连接成功");

    //插入一条管理员的账号
    const User = require("./model/User");
    //findOne查询一条
    const result = await User.findOne({ username: "admin" });
    if (!result) {
      //User.create 在User中创建账号
      await User.create({
        username: "admin",
        password: md5("123456"),
      });
    }

    // 启动服务器
    const app = express();

    // 使用中间件处理参数
    app.use(express.json()); //json格式    '{"a": 1, "b": 2}'
    app.use(express.urlencoded()); //url-encode a=1&b=2

    // 使用路由处理请求
    app.use("/api/auth", authRouter);
    app.use("/api/role", roleRouter);
    app.use("/api/admin", adminRouter)
    app.listen(8000, "localhost", () => {
      console.log("服务器启动成功....");
    });
  })
  .catch((error) => {
    console.log("数据库连接失败:", error);
  });

//http://localhost:8000/api/auth/login
